package com.innext.kjqb.ui.lend.fragment;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import com.innext.kjqb.events.AuthenticationCenterDataEvent;
import com.innext.kjqb.widget.LockableScrollView;
import com.innext.kjqb.R;
import com.innext.kjqb.app.App;
import com.innext.kjqb.base.BaseFragment;
import com.innext.kjqb.base.PermissionsListener;
import com.innext.kjqb.config.Constant;
import com.innext.kjqb.dialog.AlertFragmentDialog;
import com.innext.kjqb.dialog.CostDetailsDialog;
import com.innext.kjqb.dialog.ZeroFragmentDialog;
import com.innext.kjqb.events.AuthenticationRefreshEvent;
import com.innext.kjqb.events.FragmentRefreshEvent;
import com.innext.kjqb.events.UIBaseEvent;
import com.innext.kjqb.ui.authentication.activity.PerfectInformationActivity;
import com.innext.kjqb.ui.authentication_new.activity.AuthenticationVerifityActivity;
import com.innext.kjqb.ui.lend.activity.BankInputPwdActivity;
import com.innext.kjqb.ui.lend.activity.LendConfirmLoanActivity;
import com.innext.kjqb.ui.lend.adapter.HomeBannerImageAdapter;
import com.innext.kjqb.ui.lend.bean.ConfirmLoanBean;
import com.innext.kjqb.ui.lend.bean.ConfirmLoanFailBean;
import com.innext.kjqb.ui.lend.bean.HomeIndexResponseBean;
import com.innext.kjqb.ui.lend.contract.LendContract;
import com.innext.kjqb.ui.lend.presenter.LendPresenter;
import com.innext.kjqb.ui.main.MainActivity;
import com.innext.kjqb.ui.main.WebViewActivity;
import com.innext.kjqb.util.CalendarUtil;
import com.innext.kjqb.util.SpUtil;
import com.innext.kjqb.util.TimeUtil;
import com.innext.kjqb.util.ToastUtil;
import com.innext.kjqb.util.Tool;
import com.innext.kjqb.widget.DrawableCenterTextView;
import com.innext.kjqb.widget.HomeSeekBar;
import com.innext.kjqb.widget.RollView;
import com.innext.kjqb.widget.ViewPagerIndicator;
import com.innext.kjqb.widget.loading.LoadingLayout;
import com.tendcloud.tenddata.TCAgent;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**********
 * 借款
 */
public class LendFragment extends BaseFragment<LendPresenter> implements OnClickListener, LendContract.View {

    @BindView(R.id.loading_layout)
    LoadingLayout mLoadingLayout;
    @BindView(R.id.roll_view)
    RollView mRollView; //滚动消息view
    @BindView(R.id.scroll_view)
    LockableScrollView mScrollView; //滚动view
    @BindView(R.id.refresh)
    SwipeRefreshLayout mRefresh;    //刷新view
    @BindView(R.id.ll_loan_content)
    LinearLayout mLlLoanContent;   //未借款时布局
    RadioGroup mRgDays; //借款日期容器
    @BindView(R.id.tv_rent_btn)
    TextView mTvRentBtn;        //登录or借款按钮
    @BindView(R.id.ll_status_content)
    LinearLayout mLlStatusContent;  //借款后布局
    @BindView(R.id.tv_loan_tag)
    TextView mTvLoanTag;    //标题
    @BindView(R.id.ll_status_item_view)
    LinearLayout mLlStatusItemView; //借款状态view
    @BindView(R.id.ll_service_fee)
    LinearLayout mLlServiceFee; //登录时查看服务费按钮
    @BindView(R.id.fl_check_service_fee)
    FrameLayout mFlCheckServiceFee; //未登录时查看服务费按钮
    @BindView(R.id.ll_surplus_status)
    LinearLayout mLlSurplusStatus;
    @BindView(R.id.tv_surplus_title)
    TextView mTvSurplusTitle;
    @BindView(R.id.tv_surplus_day)
    TextView mTvSurplusDay;

    @BindView(R.id.tv_surplus_btn)
    DrawableCenterTextView mTvSurplusBtn;
    @BindView(R.id.tv_remind)
    TextView mTvRemind;
    @BindView(R.id.ll_student_tip)
    LinearLayout mStudentTipLayout;
    @BindView(R.id.viewPager)
    ViewPager mViewPage;
    @BindView(R.id.vpIndicator)
    ViewPagerIndicator mPagerIndicator;
    @BindView(R.id.tv_skip)
    TextView mTvSkip;
    @BindView(R.id.tv_skip_souyijie)
    TextView mTvSkipsouyijie;
    @BindView(R.id.ll_activateMoney)
    LinearLayout mActivateMoneyLayout;
    @BindView(R.id.ll_MoneyAndDay)
    LinearLayout mMoneyDayLayout;
    @BindView(R.id.iv_finger)
    ImageView mFingerImage;
    @BindView(R.id.iv_activate)
    ImageView mActivateImage;
    @BindView(R.id.iv_calculate)
    ImageView mCalculateImage;
    @BindView(R.id.tv_authentication_statu)
    TextView mAuthenticationStatu;
    @BindView(R.id.iv_finger_static)
    ImageView mFingerImageStatic;
    @BindView(R.id.iv_information)
    ImageView mInformationImage;
    @BindView(R.id.tv_loanMoney)
    TextView mLoanMoneyText;
    @BindView(R.id.tv_loanDay)
    TextView mLoanDayText;
    @BindView(R.id.sb_money)
    HomeSeekBar mMoneySeekBar;
    @BindView(R.id.sb_day)
    HomeSeekBar mDaySeekBar;
    @BindView(R.id.tv_minMoney)
    TextView mMinMoneyText;
    @BindView(R.id.tv_maxMoney)
    TextView mMaxMoneyText;
    @BindView(R.id.tv_minDay)
    TextView mMinDayText;
    @BindView(R.id.tv_maxDay)
    TextView mMaxDayText;
    @BindView(R.id.tv_RepayMoney)
    TextView mShouldReapayMoney;
    @BindView(R.id.tv_total_profit)
    TextView mTotalProfitText;
    @BindView(R.id.iv_dayRotation)
    ImageView mDayRotationImage;

    public static LendFragment lendFragment;
    private HomeIndexResponseBean.ItemBean bean;
    private ConfirmLoanFailBean.DateBean dataBean;
    private int maxMoney, loanMoney;
    private int loanDay;
    private double realMoney;
    private int realMaxMoney;
    private int realMaxDay;
    private double serviceMoney;
    private int authStep;
    private String phoneUrl;
    private String zmxyUrl;
    private String intoMoney; //还款金额
    private String loanEndTime; //还款时间
    private int surplusDay; //剩余还款天数
    private int nextLoanDay; //剩余可借款时间倒计时
    private HomeIndexResponseBean.AmountDaysListBean moneyPeriodBean;
    private List<HomeIndexResponseBean.IndexImagesBean> mActivityListBean = new ArrayList<>();
    private ImageHandler playHandler = new ImageHandler(new WeakReference<LendFragment>(this));
    private HomeBannerImageAdapter homeBannerImageAdapter;
    private MainActivity mainActivity;
    private String repaymentUrl;
    HomeIndexResponseBean.ItemBean.LoanInfosBean loaninfo;
    private ObjectAnimator scaleAnim, translationAnim, scaleAnimTwo;
    private String mType_failed;//借款失败消息
    private double creditVetMoney;
    private double accountManageMoney;
    private double accrualMoney;

    public static LendFragment getInstance() {
        if (lendFragment == null) {
            lendFragment = new LendFragment();
        }
        return lendFragment;
    }

    @Override
    public int getLayoutId() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//处理4.4的
            Window window = getActivity().getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//处理5.0以上的状态灰色背景
            Window window = getActivity().getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
//                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
            );
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION  //该参数指布局能延伸到navigationbar
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Color.TRANSPARENT); //设置navigationbar颜色为透明
        }
        return R.layout.fragment_lend_main;
    }

    @Override
    public void initPresenter() {
        mPresenter.init(this);
    }

    @Override
    public void loadData() {
        mainActivity = (MainActivity) mActivity;
        EventBus.getDefault().register(this);
        initView();
        initListener();
    }

    private void initView() {
//        mTitle.setTitle(false, App.getAPPName());
        mRefresh.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.theme_color));
        //加载数据
        mLoadingLayout.setStatus(LoadingLayout.Loading);
        mPresenter.loadIndex();
    }

    @Override
    public void indexSuccess(HomeIndexResponseBean result) {
        mLoadingLayout.setStatus(LoadingLayout.Success);
        bean = result.getItem();
        EventBus.getDefault().post(
                new AuthenticationCenterDataEvent(bean.getAuthStep(), bean.getPhoneInfoUrl(), bean.getRiskCarditInfoUrl()));
        //金额集合
        List<Integer> amounts = result.getAmount_days_list().getAmounts();
        List<HomeIndexResponseBean.AmountDaysListBean.DaysListBean> days = result.getAmount_days_list().getDaysList();
        if (amounts != null && amounts.size() > 2) {
            //需求：只能借整百
            //获取最大金额值
            realMaxMoney = amounts.get(amounts.size() - 1);
            //如果最后一个值与倒数第二位相等或者最后一个值除100不等于0，则去除最后一个值
            if (amounts.get(amounts.size() - 1).equals(amounts.get(amounts.size() - 2)) || amounts.get(amounts.size() - 1) % 10000 != 0) {
                amounts.remove(amounts.size() - 1);
            }
        }
        if (days != null && days.size() >= 2) {
            //获取最大的天数
            realMaxDay = (days.size() - 1) * 100;
            mMinDayText.setVisibility(View.VISIBLE);
            mMinDayText.setText(days.get(0).getDays() + "天");
            mMaxDayText.setText(days.get(days.size() - 1).getDays() + "天");
            loanDay=Integer.parseInt(days.get(days.size() - 1).getDays());
        } else {
            realMaxDay = Integer.parseInt(days.get(days.size() - 1).getDays()) * 100;
            mMinDayText.setVisibility(View.GONE);
            mMaxDayText.setText(days.get(days.size() - 1).getDays() + "天");
            loanDay=Integer.parseInt(days.get(days.size() - 1).getDays());
        }
        //金额集合
        moneyPeriodBean = result.getAmount_days_list();
        // 借款滚动信息
        mRollView.setContent(result.getUser_loan_log_list());
        //热门活动集合
        mActivityListBean = result.getIndex_images();

        mMoneySeekBar.setMax(realMaxMoney / 10000*100);
        mMoneySeekBar.setProgress(realMaxMoney / 10000*100);
//        mMoneySeekBar.setAnimProgress(maxMoney, false);
        mDaySeekBar.setMax(realMaxDay);
        mDaySeekBar.setProgress(realMaxDay);
//        mDaySeekBar.setAnimProgress(maxMoney, false);
        mMinMoneyText.setText(amounts.get(0) / 10000*100 + "元");
        mMaxMoneyText.setText(realMaxMoney / 10000*100 + "元");
        mLoanMoneyText.setText(realMaxMoney / 10000*100+"");
        loanMoney=moneyPeriodBean.getAmounts().get(amounts.size()-1)/100;
        calculateRate(moneyPeriodBean.getDaysList());
        initViewPager();
        //获取数据后进行显示在界面上
        setZeroMoneyEvent();
        setData();
        mHandler.sendEmptyMessage(1);
//        setWheelView();
        setSeekBar();
    }


    private void setSeekBar() {
        mMoneySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                if (moneyPeriodBean == null) {
                    return;
                }
                int position = (progress + 50) / 100;
                if (position >= moneyPeriodBean.getAmounts().size()) {
                    position = moneyPeriodBean.getAmounts().size() - 1;
                }
                loanMoney = moneyPeriodBean.getAmounts().get(position) / 100;
                //下面到账金额的改变
                calculateRate(moneyPeriodBean.getDaysList());
                mLoanMoneyText.setText(loanMoney + "");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                seekBar.setProgress((mMoneySeekBar.getProgress() + 50) / 100 * 100);
            }
        });

        mDaySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                if (moneyPeriodBean == null) {
                    return;
                }
                int position = (progress + 50) / 100;
                if (position >= moneyPeriodBean.getDaysList().size()) {
                    position = moneyPeriodBean.getDaysList().size() - 1;
                }
                loanDay = Integer.parseInt((moneyPeriodBean.getDaysList().get(position).getDays()));
//                loanDay = moneyPeriodBean.getDays().get((progress + 50) / 100);
                //下面到账金额的改变
                calculateRate(moneyPeriodBean.getDaysList());
                mLoanDayText.setText(loanDay + "");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                seekBar.setProgress((mDaySeekBar.getProgress() + 50) / 100 * 100);
            }
        });
    }


    /**
     * 额度为0的操作；
     */
    private void setZeroMoneyEvent() {
        if (moneyPeriodBean.getAmounts().size() == 2 && moneyPeriodBean.getAmounts().get(0) == 0) {
            mTvRentBtn.setVisibility(View.GONE);
            mTvSkipsouyijie.setVisibility(View.VISIBLE);
        } else {
            mTvRentBtn.setVisibility(View.VISIBLE);
            mTvSkipsouyijie.setVisibility(View.GONE);
        }

        if (!Tool.isBlank(bean.getGuide_url())) {
            //缓存图片url与点击url。
            String imgUrl = SpUtil.getString(Constant.CACHE_TAG_ZERO_IMGURL);
            if (!bean.getGuide_url().equals(imgUrl)) {
                SpUtil.putString(Constant.CACHE_TAG_ZERO_IMGURL, bean.getGuide_url());
                ZeroFragmentDialog.newInstance(bean.getGuide_url(), bean.getMention_the_forehead_url())
                        .show(mActivity.getSupportFragmentManager(), ZeroFragmentDialog.TAG);
            }
        }
    }

    @Override
    public void toLoanSuccess(ConfirmLoanBean result) {
        Intent intent = new Intent(getActivity(), LendConfirmLoanActivity.class);
        intent.putExtra(BankInputPwdActivity.TAG_OPERATE_BEAN, result);
        startActivity(intent);
    }

    @Override
    public void confirmFailedSuccess() {
        mPresenter.loadIndex();
        if (loaninfo != null) {
            Intent intent = new Intent(getActivity(), WebViewActivity.class);
            intent.putExtra("url", loaninfo.getBankUrl());
            startActivity(intent);
        }
        EventBus.getDefault().post(new FragmentRefreshEvent(UIBaseEvent.EVENT_LOAN_FAILED));
    }

    @Override
    public void showLoading(String content) {
        if (bean != null) {
        }
    }

    @Override
    public void stopLoading() {
        if (mRefresh.isRefreshing()) {
            mRefresh.setRefreshing(false);
        }
    }

    /**
     * @param msg  请求异常信息
     * @param type 若有多个请求，用于区分不同请求（不同请求失败或有不同的处理）
     */
    @Override
    public void showErrorMsg(String msg, String type) {
        if (TextUtils.isEmpty(type)) {
            return;
        }
        if (type.equals(mPresenter.TYPE_INDEX)) {//首页接口
            ToastUtil.showToast(msg);
            loadingStatusView(msg);
        } else if (type.equals(mPresenter.TYPE_FAILED)) { //借款失败调用
            mType_failed = mPresenter.TYPE_FAILED;
            mPresenter.loadIndex();
        } else if (type.equals(mPresenter.TYPE_LOAN)) {   //验证借款信息
            ToastUtil.showToast(msg);
        }
    }

    //为view设置数据
    private void setData() {
        if (bean != null) {
            EventBus.getDefault().post(
                    new AuthenticationCenterDataEvent(bean.getAuthStep(), bean.getPhoneInfoUrl(), bean.getRiskCarditInfoUrl()));
            Log.i("mAuthStep-LendFragment", bean.getAuthStep() + "");
            //设置站内信图标
            if (!Tool.isBlank(bean.getMainCount() + "")) {

                if (bean.getMainCount() > 0) {
                    mInformationImage.setImageResource(R.mipmap.info_point_icon);
                    mInformationImage.setOnClickListener(infomationClickListener);
                } else {
                    mInformationImage.setImageResource(R.mipmap.icon_message);
                    mInformationImage.setOnClickListener(infomationClickListener);
                }
            }
            if (!Tool.isBlank(bean.getAuthStep() + "")) {
                authStep = bean.getAuthStep();
            }
            if (!TextUtils.isEmpty(bean.getPhoneInfoUrl())) {
                phoneUrl = bean.getPhoneInfoUrl();
            }
            if (!TextUtils.isEmpty(bean.getRiskCarditInfoUrl())) {
                zmxyUrl = bean.getRiskCarditInfoUrl();
            }


            //认证状态
            if (bean.getVerify_loan_pass() == 1) {//已认证
                mLlServiceFee.setVisibility(View.VISIBLE);
                mFlCheckServiceFee.setVisibility(View.GONE);
                mTvRentBtn.setText("立即申请");
                if (!TextUtils.isEmpty(bean.getEvaluation_flag_status())) {
                    if (bean.getEvaluation_flag_status().equals("0")) {//认证完，计算额度
                        //                    scaleAnim.end();
                        MobclickAgent.onEvent(getContext(), "skimHome_Evaluating");
                        TCAgent.onEvent(getContext(), "skimHome_Evaluating");
                        mMoneyDayLayout.setVisibility(View.GONE);
                        mActivateMoneyLayout.setVisibility(View.VISIBLE);//打开评估布局
                        mActivateImage.setVisibility(View.VISIBLE);
                        mFingerImage.setVisibility(View.GONE);
                        mFingerImageStatic.setVisibility(View.VISIBLE);
                        mCalculateImage.setVisibility(View.VISIBLE);
                        mAuthenticationStatu.setText("额度评估中...");
                        LinearInterpolator interpolator = new LinearInterpolator();
                        translationAnim = ObjectAnimator.ofFloat(mCalculateImage, "rotation", 0, 360);
                        translationAnim.setDuration(1500);
                        translationAnim.setRepeatCount(-1);
                        translationAnim.setInterpolator(interpolator);
                        translationAnim.start();
                        mFingerImageStatic.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (!TextUtils.isEmpty(bean.getEvaluationFlagMsg())) {

                                    new AlertFragmentDialog.Builder(mActivity)
                                            .setContent(bean.getEvaluationFlagMsg())
                                            .setRightBtnText("朕知道了")
                                            .setRightCallBack(new AlertFragmentDialog.RightClickCallBack() {
                                                @Override
                                                public void dialogRightBtnClick() {
                                                }
                                            }).setCancel(false).build();
                                }
                            }
                        });
                    } else if (bean.getEvaluation_flag_status().equals("1")) {//评估额度值和是否为0额度
                        if (moneyPeriodBean.getAmounts().size() == 2) {//说明额度是0
                            //                        translationAnim.end();
                            MobclickAgent.onEvent(getContext(), "skimHome_NoCreditLine");
                            TCAgent.onEvent(getContext(), "skimHome_NoCreditLine");
                            mMoneyDayLayout.setVisibility(View.GONE);
                            mActivateMoneyLayout.setVisibility(View.VISIBLE);//打开评估布局
                            mActivateImage.setVisibility(View.VISIBLE);
                            mCalculateImage.setVisibility(View.GONE);
                            mFingerImage.setVisibility(View.VISIBLE);
                            mFingerImageStatic.setVisibility(View.GONE);
                            mAuthenticationStatu.setText("当前无额度，点击按钮有惊喜");
                            PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1f, 1.2f, 1f);
                            PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1f, 1.2f, 1f);
                            scaleAnimTwo = ObjectAnimator.ofPropertyValuesHolder(mFingerImage, scaleX, scaleY);
                            scaleAnimTwo.setDuration(2000);
                            scaleAnimTwo.setRepeatCount(-1);
                            scaleAnimTwo.start();
                            mFingerImage.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (!Tool.isBlank(bean.getMention_the_forehead_url())) {
                                        MobclickAgent.onEvent(getContext(), "Home_NoCreditLine");
                                        TCAgent.onEvent(getContext(), "Home_NoCreditLine");
                                        Intent intent = new Intent(getActivity(), WebViewActivity.class);
                                        intent.putExtra("improveUrl", bean.getMention_the_forehead_url());
                                        startActivity(intent);
                                    }
                                }
                            });
                        } else {//额度不是0
                            MobclickAgent.onEvent(getContext(), "skimHome_ApplyBorrow");
                            TCAgent.onEvent(getContext(), "skimHome_ApplyBorrow");
                            mActivateMoneyLayout.setVisibility(View.GONE);
                            mMoneyDayLayout.setVisibility(View.VISIBLE);
                        }
                    }
                }
            } else {//没认证下的情况
                if (App.getConfig().getLoginStatus()) {
                    if (TextUtils.isEmpty(bean.getEvaluation_flag_status())) {
                        MobclickAgent.onEvent(getContext(), "skimHome_NoActivate");
                        TCAgent.onEvent(getContext(), "skimHome_NoActivate");
                        mMoneyDayLayout.setVisibility(View.GONE);
                        mActivateMoneyLayout.setVisibility(View.VISIBLE);//打开评估布局
                        mActivateImage.setVisibility(View.VISIBLE);
                        mCalculateImage.setVisibility(View.GONE);
                        mFingerImage.setVisibility(View.VISIBLE);
                        mFingerImageStatic.setVisibility(View.GONE);
                        mAuthenticationStatu.setText("请点击按钮获取借款额度");
                        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1f, 1.2f, 1f);
                        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1f, 1.2f, 1f);
                        scaleAnim = ObjectAnimator.ofPropertyValuesHolder(mFingerImage, scaleX, scaleY);
                        scaleAnim.setDuration(2000);
                        scaleAnim.setRepeatCount(-1);
                        scaleAnim.start();
                        mActivateImage.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                MobclickAgent.onEvent(getContext(), "Home_NoActivate");
                                TCAgent.onEvent(getContext(), "Home_NoActivate");
                                Intent intent = new Intent(getActivity(), AuthenticationVerifityActivity.class);
                                intent.putExtra("authStep", bean.getAuthStep());
                                intent.putExtra("phoneUrl", bean.getPhoneInfoUrl());
                                intent.putExtra("zmxyUrl", bean.getRiskCarditInfoUrl());
                                startActivity(intent);
                            }
                        });
                    }
                } else {
                    mActivateMoneyLayout.setVisibility(View.GONE);
                    mMoneyDayLayout.setVisibility(View.VISIBLE);
                    mLlServiceFee.setVisibility(View.GONE);
                    mFlCheckServiceFee.setVisibility(View.VISIBLE);
                    mTvRentBtn.setText("立即申请");
                }
            }

            //借款状态  bean.getLoan_infos()不为空时为已登录并借款
            if (bean.getLoan_infos() != null) {
                MobclickAgent.onEvent(getContext(), "skimHome_Borrowing");
                TCAgent.onEvent(getContext(), "skimHome_Borrowing");
                showView(mLlStatusContent);
                setLoanStatus();
            } else {// 没有借款
                MobclickAgent.onEvent(getContext(), "skimHome_BorrowFail");
                TCAgent.onEvent(getContext(), "skimHome_BorrowFail");
                nextLoanDay = bean.getNext_loan_day();
                if (nextLoanDay > 0 && App.getConfig().getLoginStatus()) {
                    String countDownTag = SpUtil.getString(Constant.CACHE_TAG_COUNT_DOWN);
                    if (TextUtils.isEmpty(countDownTag) || !countDownTag.equals(Constant.CACHE_TAG_NEXT_LOAN)) {
                        SpUtil.putString(Constant.CACHE_TAG_COUNT_DOWN, Constant.CACHE_TAG_NEXT_LOAN);
                    }
                    showView(mLlSurplusStatus);
                } else {
                    showView(mLlLoanContent);
                    if (moneyPeriodBean != null) {
                        List<Integer> amounts = moneyPeriodBean.getAmounts();
                        if (amounts != null && amounts.size() >= 2) {
                            maxMoney = (amounts.size() - 1) * 100;
                        } else {
                            maxMoney = 0;
                        }
                    }
                }

            }
        }
    }

    //审核状态改变
    private void setLoanStatus() {
        mLlStatusItemView.removeAllViews();
        loaninfo = bean.getLoan_infos();
        mTvLoanTag.setText(loaninfo.getHeader_tip());
        List<HomeIndexResponseBean.ItemBean.LoanInfosBean.ListsBean> loans = loaninfo.getLists();
        repaymentUrl = loaninfo.getRepaymentUrl();
        if (loans != null && loans.size() > 0) {
            for (int i = 0; i < loans.size(); i++) {
                HomeIndexResponseBean.ItemBean.LoanInfosBean.ListsBean loan = loans.get(i);
                if (i == 0) {
                    addLoanStatusView(loan, R.layout.layout_loan_status_item1, i);
                } else if (i == loans.size() - 1) {
                    addLoanStatusView(loan, R.layout.layout_loan_status_item3, i);
                } else {
                    addLoanStatusView(loan, R.layout.layout_loan_status_item2, i);
                }
            }
        }
        HomeIndexResponseBean.ItemBean.LoanInfosBean.ButtonBean button = loaninfo.getButton();
        nextLoanDay = bean.getNext_loan_day();
        if (nextLoanDay != 0) {
            String countDownTag = SpUtil.getString(Constant.CACHE_TAG_COUNT_DOWN);
            if (TextUtils.isEmpty(countDownTag) || !countDownTag.equals(Constant.CACHE_TAG_NEXT_LOAN)) {
                SpUtil.putString(Constant.CACHE_TAG_COUNT_DOWN, Constant.CACHE_TAG_NEXT_LOAN);
            }
            showView(mLlSurplusStatus);
        } else {
            if (button != null) {
                final String orderId = button.getId();
                View btnLayout = LayoutInflater.from(getActivity()).inflate(R.layout.layout_loan_status_button, null);
                TextView tv_ikonw_btn = (TextView) btnLayout.findViewById(R.id.tv_ikonw_btn);
                tv_ikonw_btn.setText(button.getMsg());
                tv_ikonw_btn.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPresenter.confirmFailed(orderId);
                    }
                });
                mLlStatusItemView.addView(btnLayout);
            }
        }
        intoMoney = loaninfo.getIntoMoney();//还款金额
        loanEndTime = loaninfo.getLoanEndTime();//还款日期 格式:2016-12-12
        surplusDay = loaninfo.getLastRepaymentD();//还款倒计时天数
        if (!Tool.isBlank(intoMoney) && !TextUtils.isEmpty(loanEndTime)) {//满足这个条件,表示当前为还款阶段
            //通知还款页面列表刷新
            EventBus.getDefault().post(new FragmentRefreshEvent(UIBaseEvent.EVENT_BORROW_MONEY_SUCCESS));

            if (!TextUtils.isEmpty(SpUtil.getString(Constant.CACHE_TAG_COUNT_DOWN)) &&
                    SpUtil.getString(Constant.CACHE_TAG_COUNT_DOWN).equals(Constant.CACHE_TAG_REPAY_COUNT_DOWN)) {
                showView(mLlSurplusStatus);
            } else {
                //切换倒计时页面
                //                View btnLayout = LayoutInflater.from(getActivity()).inflate(R.layout.layout_loan_status_button, null);
                //                TextView tv_ikonw_btn = (TextView) btnLayout.findViewById(R.id.tv_ikonw_btn);
                //                tv_ikonw_btn.setText("我知道了");
                //                tv_ikonw_btn.setOnClickListener(new OnClickListener() {
                //                    @Override
                //                    public void onClick(View v) {
                //                        SpUtil.putString(Constant.CACHE_TAG_COUNT_DOWN, Constant.CACHE_TAG_REPAY_COUNT_DOWN);
                //                        showView(mLlSurplusStatus);
                //                    }
                //                });
                //                mLlStatusItemView.addView(btnLayout);
                SpUtil.putString(Constant.CACHE_TAG_COUNT_DOWN, Constant.CACHE_TAG_REPAY_COUNT_DOWN);
                showView(mLlSurplusStatus);
            }

            showCalenderDialog();
        }
    }

    /**
     * 切换 未借款、借款中。倒计时布局
     *
     * @param view
     */
    private void showView(View view) {
        switch (view.getId()) {
            case R.id.ll_loan_content:
                mLlLoanContent.setVisibility(View.VISIBLE);
                mLlStatusContent.setVisibility(View.GONE);
                mLlSurplusStatus.setVisibility(View.GONE);
                break;
            case R.id.ll_status_content:
                mLlLoanContent.setVisibility(View.GONE);
                mLlStatusContent.setVisibility(View.VISIBLE);
                mLlSurplusStatus.setVisibility(View.GONE);
                break;
            case R.id.ll_surplus_status:
                mLlLoanContent.setVisibility(View.GONE);
                mLlStatusContent.setVisibility(View.GONE);
                mLlSurplusStatus.setVisibility(View.VISIBLE);
                LinearInterpolator interpolator = new LinearInterpolator();
                ObjectAnimator Animator = ObjectAnimator.ofFloat(mDayRotationImage, "rotation", 0, 360);
                Animator.setDuration(1500);
                Animator.setRepeatCount(-1);
                Animator.setInterpolator(interpolator);
                Animator.start();
                if (SpUtil.getString(Constant.CACHE_TAG_COUNT_DOWN).equals(Constant.CACHE_TAG_REPAY_COUNT_DOWN)) {

                    if (surplusDay < 0) {
                        MobclickAgent.onEvent(getContext(), "skimHome_Expired");
                        TCAgent.onEvent(getContext(), "skimHome_Expired");
                        mTvSurplusTitle.setText("本次已逾期时间:(天)");
                        mTvSkip.setVisibility(View.VISIBLE);
                    } else {
                        MobclickAgent.onEvent(getContext(), "skimHome_WaitReply");
                        TCAgent.onEvent(getContext(), "skimHome_WaitReply");
                        mTvSurplusTitle.setText("距离本次还款时间还剩:(天)");
                        mTvSkip.setVisibility(View.GONE);
                    }
                    mTvSurplusBtn.setText("现在就还");
                    if (!Tool.isBlank(repaymentUrl)) {
                        mTvSurplusBtn.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (surplusDay < 0) {
                                    MobclickAgent.onEvent(getContext(), "Home_QuickRepay");
                                    TCAgent.onEvent(getContext(), "Home_QuickRepay");
                                } else {
                                    MobclickAgent.onEvent(getContext(), "Home_NowRepay");
                                    TCAgent.onEvent(getContext(), "Home_NowRepay");
                                }
                                Intent repayIntent = new Intent(mActivity, WebViewActivity.class);
                                repayIntent.putExtra("url", repaymentUrl);
                                startActivity(repayIntent);
                            }
                        });
                    }
                    mTvSurplusBtn.setEnabled(true);
                    mTvSurplusBtn.setGravity(Gravity.CENTER);
                    mTvSurplusBtn.setCompoundDrawablePadding(0);
                    mTvSurplusBtn.setCompoundDrawables(null, null, null, null);
                    mTvSurplusDay.setText(String.valueOf(Math.abs(surplusDay)).length() == 1 ? (surplusDay == 0 ? String.valueOf(surplusDay) : "0" + Math.abs(surplusDay)) : String.valueOf(Math.abs(surplusDay)));
                } else if (SpUtil.getString(Constant.CACHE_TAG_COUNT_DOWN).equals(Constant.CACHE_TAG_NEXT_LOAN)) {
                    mTvSurplusTitle.setText("距离下次申请时间还剩:(天)");
                    if (!Tool.isBlank(bean.getGuide_url())) {
                        //缓存图片url与点击url。
                        String imgUrl = SpUtil.getString(Constant.CACHE_TAG_FAIL_IMGURL);
                        if (!bean.getGuide_url().equals(imgUrl)) {
                            SpUtil.putString(Constant.CACHE_TAG_FAIL_IMGURL, bean.getGuide_url());
                            ZeroFragmentDialog.newInstance(bean.getGuide_url(), bean.getMention_the_forehead_url())
                                    .show(mActivity.getSupportFragmentManager(), ZeroFragmentDialog.TAG);
                        }
                    }
                    //                    mTvSkip.setVisibility(View.GONE);
                    String nowLoanDate = TimeUtil.getCurrentDateByOffset("yyyy-MM-dd 00:00:00", Calendar.DAY_OF_MONTH, nextLoanDay);
                    if (TextUtils.isEmpty(SpUtil.getString(Constant.CACHE_CALENDAR_LOAN_DATE)) ||
                            !SpUtil.getString(Constant.CACHE_CALENDAR_LOAN_DATE).equals(nowLoanDate)) {
                        mTvSurplusBtn.setText("提醒我");
                        mTvSurplusBtn.setEnabled(true);
                        mTvSkip.setVisibility(View.VISIBLE);
                    } else {
                        mTvSurplusBtn.setText("已添加提醒");
                        mTvSurplusBtn.setEnabled(false);
                        mTvSkip.setVisibility(View.VISIBLE);
                    }
                    mTvSurplusBtn.setGravity(Gravity.CENTER_VERTICAL);
                    Drawable left = ContextCompat.getDrawable(mActivity, R.mipmap.remind);
                    left.setBounds(0, 0, left.getMinimumWidth(), left.getMinimumHeight());
                    mTvSurplusBtn.setCompoundDrawables(left, null, null, null);
                    mTvSurplusBtn.setCompoundDrawablePadding(Tool.dip2px(mContext, 5));
                    mTvSurplusDay.setText(String.valueOf(nextLoanDay).length() == 1 ? (nextLoanDay == 0 ? String.valueOf(nextLoanDay) : "0" + nextLoanDay) : String.valueOf(nextLoanDay));
                }
                break;
        }
    }

    private AlertFragmentDialog dialog;

    /**
     * 日历功能
     */
    private void showCalenderDialog() {
        String calendarPermissions = SpUtil.getString(Constant.CACHE_CALENDAR_PERMISSIONS);
        boolean permissions = ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_DENIED;
        //未授权则弹出框
        if (TextUtils.isEmpty(calendarPermissions) && permissions) {
            if (dialog == null) {
                dialog = new AlertFragmentDialog.Builder(mActivity).setLeftBtnText("不允许")
                        .setLeftCallBack(new AlertFragmentDialog.LeftClickCallBack() {
                            @Override
                            public void dialogLeftBtnClick() {
                                SpUtil.putString(Constant.CACHE_CALENDAR_PERMISSIONS, "no");
                            }
                        })
                        .setRightBtnText("允许")
                        .setContent("开启日历还款提醒，不再忘记还钱，更快提升额度。")
                        .setRightCallBack(new AlertFragmentDialog.RightClickCallBack() {
                            @Override
                            public void dialogRightBtnClick() {
                                requestPermissions(new String[]{Manifest.permission.WRITE_CALENDAR}, new PermissionsListener() {
                                    @Override
                                    public void onGranted() {
                                        insetCalender();
                                    }

                                    @Override
                                    public void onDenied(List<String> deniedPermissions, boolean isNeverAsk) {
                                        SpUtil.putString(Constant.CACHE_CALENDAR_PERMISSIONS, "no");
                                    }
                                });
                            }
                        }).build();
            } else if (!dialog.getShowsDialog()) {
                dialog.show(getChildFragmentManager(), AlertFragmentDialog.TAG);
            }
        } else if (calendarPermissions.equals("yes") || !permissions) {
            insetCalender();
        }
    }

    /**
     * 插入日历
     */
    private void insetCalender() {
        //往日历中插数据
        final String mLoanEndTime = SpUtil.getString(Constant.CACHE_CALENDAR_REPAY_DATE);//获取缓存的还款日期
        String mLoanEndMoney = SpUtil.getString(Constant.CACHE_CALENDAR_REPAY_MONEY); //获取缓存的还款金额
        if (TextUtils.isEmpty(mLoanEndTime) || !mLoanEndTime.equals(loanEndTime) ||
                !mLoanEndMoney.equals(intoMoney)) {//缓存的日期为空或者与返回的日期不相等，则去日历插入
            mActivity.requestPermissions(new String[]{Manifest.permission.WRITE_CALENDAR}, new PermissionsListener() {
                @Override
                public void onGranted() {
                    SpUtil.putString(Constant.CACHE_CALENDAR_PERMISSIONS, "yes");
                    CalendarUtil.deleteCalendarEvent(mContext, App.getAPPName());
                    String refundDate = loanEndTime;//还款日期 2017-01-06格式
                    String refundAmount = intoMoney;//还款金额
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
                    String time = refundDate + " 00:00:00";
                    Date date = null;
                    long mFinalTime = 0;
                    try {
                        date = format.parse(time);
                        long dateTime = date.getTime();
                        mFinalTime = dateTime - 14 * 60 * 60 * 1000;//还款日的前一天10:00提示
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    String fomater = CalendarUtil.dateFomater(refundDate);
                    if (CalendarUtil.addCalendarEvent(getContext(),
                            App.getAPPName(), "明天" + fomater + ",极速现金侠需还款" + refundAmount + "元(如已提前还款请忽略)",
                            mFinalTime)) {
                        SpUtil.putString(Constant.CACHE_CALENDAR_REPAY_DATE, loanEndTime);
                        SpUtil.putString(Constant.CACHE_CALENDAR_REPAY_MONEY, intoMoney);
                    }
                }

                @Override
                public void onDenied(List<String> deniedPermissions, boolean isNeverAsk) {
                    SpUtil.putString(Constant.CACHE_CALENDAR_PERMISSIONS, "no");
                    ToastUtil.showToast("日历提醒已被禁止,如有需要,请手动开启");
                }
            });
        }
    }

    /**
     * 加载借款时状态布局
     *
     * @param loan
     * @param layout
     */
    private void addLoanStatusView(HomeIndexResponseBean.ItemBean.LoanInfosBean.ListsBean loan, int layout, int position) {
        View content = LayoutInflater.from(getActivity()).inflate(layout, null);
        ImageView item_icon = (ImageView) content.findViewById(R.id.item_icon);
        View item_line = content.findViewById(R.id.item_line);
        if (position == 0 || position == 1) {
            item_line.setBackgroundResource(R.mipmap.icon_dashed);
        }
        TextView tv_title = (TextView) content.findViewById(R.id.tv_title);
        TextView tv_info = (TextView) content.findViewById(R.id.tv_info);
        tv_title.setText(Html.fromHtml(loan.getTitle()));
        tv_info.setText(loan.getBody());
        if (loan.getTag() == 0) {
            item_icon.setImageResource(R.mipmap.icon_loan_status_passed);
            tv_title.setTextColor(ContextCompat.getColor(mContext, R.color.global_label_color));
            tv_info.setTextColor(ContextCompat.getColor(mContext, R.color.global_label_color));
        } else if (loan.getTag() == 1) {
            item_icon.setImageResource(R.mipmap.state_underway);
            tv_title.setTextColor(ContextCompat.getColor(mContext, R.color.global_black_color));
            tv_info.setTextColor(ContextCompat.getColor(mContext, R.color.global_black_color));
        } else if (loan.getTag() == 2) {
            item_icon.setImageResource(R.mipmap.icon_loan_status_nopassed);
            tv_title.setTextColor(ContextCompat.getColor(mContext, R.color.global_black_color));
            tv_info.setTextColor(ContextCompat.getColor(mContext, R.color.global_black_color));
        } else if (loan.getTag() == 3) {
            item_icon.setImageResource(R.mipmap.state_done);
            tv_title.setTextColor(ContextCompat.getColor(mContext, R.color.global_black_color));
            tv_info.setTextColor(ContextCompat.getColor(mContext, R.color.global_black_color));
        }
        mLlStatusItemView.addView(content);
    }

    private void loadingStatusView(String message) {
        if ("网络不可用".equals(message)) {

        } else {
            mLoadingLayout.setErrorText(message)
                    .setStatus(LoadingLayout.Error);
        }
        mLoadingLayout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                mPresenter.loadIndex();
            }
        });
    }

    private void initListener() {
        mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.loadIndex();
            }
        });
    }

    @OnClick({R.id.tv_total_profit, R.id.ll_student_tip, R.id.tv_rent_btn, R.id.fl_check_service_fee, R.id.tv_surplus_btn, R.id.tv_remind, R.id.tv_skip, R.id.tv_skip_souyijie})
    public void onClick(View v) {
        if (Tool.isFastDoubleClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.tv_skip:
                if (surplusDay < 0) {
                    //逾期点击埋点
                    MobclickAgent.onEvent(getContext(), "Expire_TryClickme");
                    TCAgent.onEvent(getContext(), "Expire_TryClickme");
                }
                if (!TextUtils.isEmpty(mType_failed)) {
                    //借款失败点击埋点
                    MobclickAgent.onEvent(getContext(), "BorrowFail_TryClickme");
                    TCAgent.onEvent(getContext(), "BorrowFail_TryClickme");
                }

                if (!Tool.isBlank(bean.getMention_the_forehead_url())) {
                    Intent intent = new Intent(getActivity(), WebViewActivity.class);
                    intent.putExtra("improveUrl", bean.getMention_the_forehead_url());
                    startActivity(intent);
                }
                break;
            case R.id.tv_total_profit:
                MobclickAgent.onEvent(getActivity(), "Home_FeeDetail");
                TCAgent.onEvent(getActivity(), "Home_FeeDetail");
                CostDetailsDialog.newInstance(creditVetMoney, accountManageMoney, accrualMoney).show(mActivity.getSupportFragmentManager(), CostDetailsDialog.TAG);
                break;
            case R.id.tv_skip_souyijie:
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("improveUrl", bean.getMention_the_forehead_url());
                startActivity(intent);
                break;
            case R.id.tv_rent_btn:  //借款按钮
                MobclickAgent.onEvent(getContext(), "Home_ApplyBorrow");
                TCAgent.onEvent(getContext(), "Home_ApplyBorrow");
                if (!App.getConfig().getLoginStatus()) {
                    App.toLogin(getActivity());
                } else {
                    if (bean.getVerify_loan_pass() == 1) {
                        toLoan();
                    } else {
                        Intent liftingQuotaIntent = new Intent(getActivity(), PerfectInformationActivity.class);
                        startActivityToLogin(liftingQuotaIntent);
                    }
                }
                break;
            case R.id.fl_check_service_fee: //未登录时查看服务费
                App.toLogin(getActivity());
                break;
            //            case R.id.ll_service_fee_check: //登录后查看服务费
            //                CostDetailsDialog.newInstance(loanMoney+"",loanDay+"").show(getChildFragmentManager(),CostDetailsDialog.TAG);
            //                break;
            case R.id.tv_surplus_btn:
                if (!TextUtils.isEmpty(mType_failed)) {
                    MobclickAgent.onEvent(getContext(), "RemindMe");
                    TCAgent.onEvent(getContext(), "RemindMe");
                }
                String status = SpUtil.getString(Constant.CACHE_TAG_COUNT_DOWN);
                if (TextUtils.isEmpty(status)) {
                    return;
                }
                if (status.contains(Constant.CACHE_TAG_REPAY_COUNT_DOWN)) {//还款倒计时
                    mainActivity.getGroup().check(R.id.rb_rent_lend);
                } else if (status.contains(Constant.CACHE_TAG_NEXT_LOAN)) {//下次可借款倒计时
                    //往日历中插数据
                    final String mLoanStartTime = SpUtil.getString(Constant.CACHE_CALENDAR_LOAN_DATE);//获取缓存的下次可借款日期
                    Log.e("----", "mLoanStartTime=" + mLoanStartTime + "loanEndTime =" + loanEndTime);
                    if (TextUtils.isEmpty(mLoanStartTime) || !mLoanStartTime.equals(loanEndTime)) {//缓存的日期为空或者与返回的日期不相等，则去日历插入
                        mActivity.requestPermissions(new String[]{Manifest.permission.WRITE_CALENDAR}, new PermissionsListener() {
                            @Override
                            public void onGranted() {
                                CalendarUtil.deleteCalendarEvent(mContext, App.getAPPName());
                                //下次可借款日期 格式:yyyy-MM-dd 00:00:00
                                String refundDate = TimeUtil.getCurrentDateByOffset("yyyy-MM-dd 00:00:00", Calendar.DAY_OF_MONTH, nextLoanDay);

                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
                                Date date;
                                long mFinalTime = 0;
                                try {
                                    date = format.parse(refundDate);
                                    long dateTime = date.getTime();
                                    mFinalTime = dateTime + 10 * 60 * 60 * 1000;//可借款日的当天10:00提示
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                if (CalendarUtil.addCalendarEvent(getContext(),
                                        App.getAPPName(), "今天" + App.getAPPName() + "可以申请借款啦",
                                        mFinalTime)) {
                                    SpUtil.putString(Constant.CACHE_CALENDAR_LOAN_DATE, refundDate);
                                    mTvSurplusBtn.setEnabled(false);
                                    mTvSurplusBtn.setText("已添加提醒");
                                }
                            }

                            @Override
                            public void onDenied(List<String> deniedPermissions, boolean isNeverAsk) {
                                SpUtil.putString(Constant.CACHE_CALENDAR_PERMISSIONS, "no");
                                if (isNeverAsk) {
                                    mActivity.toAppSettings("日历权限已被禁止", false);
                                }
                            }
                        });
                    }
                }
                break;
            case R.id.tv_remind:
                String url = App.getConfig().ACTIVITY_DETAILS;
                Intent intents = new Intent(getActivity(), WebViewActivity.class);
                intents.putExtra("url", url);
                startActivity(intents);
                break;
            case R.id.ll_student_tip:
                String urlTip = App.getConfig().ACTIVITY_DETAILS;
                Intent intentTip = new Intent(getActivity(), WebViewActivity.class);
                intentTip.putExtra("url", urlTip);
                startActivity(intentTip);
                break;
            default:
                break;
        }
    }

    /**
     * 当天数选择的时候，计算费用
     */
    private void calculateRate(List<HomeIndexResponseBean.AmountDaysListBean.DaysListBean> amountDaysList) {

        if (loanMoney == 0) {
        } else {
            if (Tool.isBlank(amountDaysList.size() + "")) {//因为后台分登陆和未登录状态导致该判断必须要；
                return;
            }
            for (int i = 0; i < amountDaysList.size(); i++) {
                if (loanDay == Integer.parseInt(amountDaysList.get(i).getDays())) {
                    double creditVet = amountDaysList.get(i).getCreditVet() / 100;
                    double accountManage = amountDaysList.get(i).getAccountManage() / 100;
                    double accrual = amountDaysList.get(i).getAccrual() / 100;
                    double offset = loanMoney * 100 / (double) realMaxMoney;
                    creditVetMoney = creditVet * offset;
                    accountManageMoney = accountManage * offset;
                    accrualMoney = accrual * offset;
                    //根据字段砍头息利息计算；
                    double totalMoney = loanMoney + creditVetMoney + accountManageMoney + accrualMoney;
                    double totalProfit = creditVetMoney + accountManageMoney + accrualMoney;
                    mTotalProfitText.setText(new DecimalFormat("0.00").format(totalProfit) + "元");
                    if (!Tool.isBlank(moneyPeriodBean.getAddServiceFeeIsopen())) {
                        if (moneyPeriodBean.getAddServiceFeeIsopen().equals("0")) {
                            mShouldReapayMoney.setText(new DecimalFormat("0.00").format(loanMoney) + "元");
                        } else {
                            mShouldReapayMoney.setText(new DecimalFormat("0.00").format(totalMoney) + "元");
                        }
                    }

                    break;
                }
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(FragmentRefreshEvent event) {
        //当借款申请成功、还款或续期成功、登录成、退出功时刷新数据
        if (event.getType() == UIBaseEvent.EVENT_LOAN_SUCCESS ||
                event.getType() == UIBaseEvent.EVENT_LOGIN ||
                event.getType() == UIBaseEvent.EVENT_REPAY_SUCCESS ||
                event.getType() == UIBaseEvent.EVENT_LOGOUT ||
                event.getType() == UIBaseEvent.REFRESHINDEX) {
            // 数据刷新
            mPresenter.loadIndex();
            if (App.getConfig().getLoginStatus()) {
                mLlServiceFee.setVisibility(View.VISIBLE);
                mFlCheckServiceFee.setVisibility(View.GONE);
                mTvRentBtn.setText("立即申请");
            } else {
                mLlServiceFee.setVisibility(View.GONE);
                mFlCheckServiceFee.setVisibility(View.VISIBLE);
                mTvRentBtn.setText("立即申请");
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAuthenticationRefresh(AuthenticationRefreshEvent event) {
        // 认证成功 数据刷新
        mPresenter.loadIndex();
    }

    private void toLoan() {
        if (loanMoney <= 0) {
            ToastUtil.showToast("借款额度为0,暂不可借款");
            return;
        }
        if (loanDay <= 0) {
            ToastUtil.showToast("借款期限错误");
            return;
        }
        if (loanMoney > (bean.getCard_amount() / 100)) {
            ToastUtil.showToast("您的最高可借额度仅为" + bean.getCard_amount() / 100 + "哦");
            return;
        }
        mPresenter.toLoan(String.valueOf(loanMoney), String.valueOf(loanDay));
    }

    //站内信
    OnClickListener infomationClickListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            MobclickAgent.onEvent(getActivity(), "Home_borrow_Bingbank");
            TCAgent.onEvent(getActivity(), "Home_borrow_Bingbank");
            String url = App.getConfig().ACTIVITY_CENTER;
            Intent intent = new Intent(getActivity(), WebViewActivity.class);
            intent.putExtra("url", url);
            startActivity(intent);
        }
    };

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mPresenter.loadIndex();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mRollView.play();
        MobclickAgent.onPageStart("首页"); //统计页面，"MainScreen"为页面名称，可自定义
        MobclickAgent.onEvent(getContext(), "lend");
        TCAgent.onPageStart(mContext, "首页");
        TCAgent.onEvent(getContext(), "lend");
    }


    @Override
    public void onPause() {
        super.onPause();
        mRollView.onStop();
        MobclickAgent.onPageEnd("首页");
        TCAgent.onPageEnd(mContext, "首页");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        lendFragment = null;
    }

    /**
     * viewPager的轮播切换
     */
    private void initViewPager() {
        Log.i("列表", mActivityListBean.size() + mActivityListBean.toString());
        if (!Tool.isBlank(mActivityListBean.size() + "")) {
            homeBannerImageAdapter = new HomeBannerImageAdapter(mActivity, mActivityListBean);
            mViewPage.setAdapter(homeBannerImageAdapter);
            mPagerIndicator.setViewPager(mViewPage, mActivityListBean.size());
            mPagerIndicator.setOnPageScroll(new ViewPager.OnPageChangeListener() {
                // 配合Adapter的currentItem字段进行设置。
                @Override
                public void onPageSelected(int arg0) {
                    playHandler.sendMessage(Message.obtain(playHandler, ImageHandler.MSG_PAGE_CHANGED, arg0, 0));
                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                }

                // 覆写该方法实现轮播效果的暂停和恢复
                @Override
                public void onPageScrollStateChanged(int arg0) {
                    switch (arg0) {
                        case ViewPager.SCROLL_STATE_DRAGGING:
                            playHandler.sendEmptyMessage(ImageHandler.MSG_KEEP_SILENT);
                            break;
                        case ViewPager.SCROLL_STATE_IDLE:
                            playHandler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE, ImageHandler.MSG_DELAY);
                            break;
                        default:
                            break;
                    }
                }
            });
            mViewPage.setCurrentItem(0);
            playHandler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE, ImageHandler.MSG_DELAY);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private static class ImageHandler extends Handler {
        /**
         * 请求更新显示的View,即进行轮播
         */
        protected static final int MSG_UPDATE_IMAGE = 1;
        /**
         * 请求暂停轮播。
         */
        protected static final int MSG_KEEP_SILENT = 2;
        /**
         * 请求恢复轮播。
         */
        protected static final int MSG_BREAK_SILENT = 3;
        /**
         * 记录最新的页号，当用户手动滑动时需要记录新页号，否则会使轮播的页面出错。
         * 例如当前如果在第一页，本来准备播放的是第二页，而这时候用户滑动到了末页，
         * 则应该播放的是第一页，如果继续按照原来的第二页播放，则逻辑上有问题。
         */
        protected static final int MSG_PAGE_CHANGED = 4;
        // 轮播间隔时间
        protected static final long MSG_DELAY = 3000;
        // 使用弱引用避免Handler泄露.这里的泛型参数可以不是Activity，也可以是Fragment等
        private WeakReference<LendFragment> weakReference;
        private int currentItem = 0;

        protected ImageHandler(WeakReference<LendFragment> wk) {
            weakReference = wk;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            LendFragment lendFragment = weakReference.get();
            if (lendFragment == null) {
                // Activity已经回收，无需再处理UI了
                return;
            }
            // 检查消息队列并移除未发送的消息，这主要是避免在复杂环境下消息出现重复等问题。
            if (lendFragment.playHandler.hasMessages(MSG_UPDATE_IMAGE)) {
                lendFragment.playHandler.removeMessages(MSG_UPDATE_IMAGE);
            }
            switch (msg.what) {
                case MSG_UPDATE_IMAGE:
                    currentItem = lendFragment.mViewPage.getCurrentItem();
                    currentItem++;
                    // currentItem = currentItem % activity.PAGE_COUNT;
                    lendFragment.mViewPage.setCurrentItem(currentItem, true);
                    lendFragment.playHandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
                    break;
                case MSG_KEEP_SILENT:
                    // 只要不发送消息就暂停了
                    break;
                case MSG_BREAK_SILENT:
                    lendFragment.playHandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
                    break;
                case MSG_PAGE_CHANGED:
                    // 记录当前的页号，避免播放的时候页面显示不正确。
                    currentItem = msg.arg1;
                    break;
                default:
                    break;
            }
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (mActivityListBean != null && mActivityListBean.size() != 0) {
                        HomeBannerImageAdapter adapter = (HomeBannerImageAdapter) mViewPage.getAdapter();
                        adapter.updateItem(mActivityListBean, mViewPage);
                        mPagerIndicator.setViewPager(mViewPage, mActivityListBean.size());
                    }
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };
}
